package com.tanhua.manager.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.UserFreeze;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.db.UserUnfreeze;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.dubbo.api.db.UserFreezeApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.db.UserUnfreezeApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.vo.CommentVo;
import com.tanhua.vo.Movements;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.VideoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;

    public ResponseEntity queryUsers(Integer page, Integer pagesize, Long id, String nickname, String city) {
        IPage<UserInfo> iPage = userInfoApi.queryUsers(page,pagesize,id,nickname,city);

        PageResult pageResult = new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());

        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity queryUserById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }


    @Reference
    private VideoApi videoApi;

    public ResponseEntity queryVideosByUserId(Integer page, Integer pagesize, Long userId) {
//        查询指定用户的小视频
        PageResult pageResult =  videoApi.queryVideosByUserId(page,pagesize,userId);
        List<Video> items = (List<Video>) pageResult.getItems();
//        Video------>VideoVo
        List<VideoVo> list = new ArrayList<>();
        for (Video video : items) {

            UserInfo userInfo = userInfoApi.findById(userId);
            if(userInfo==null){  //为了防止垃圾数据
                continue;
            }
            VideoVo videoVo = new VideoVo();

            BeanUtils.copyProperties(video,videoVo);
            videoVo.setId(video.getId().toString());
            videoVo.setCover(video.getPicUrl());
            videoVo.setSignature(video.getText());

            BeanUtils.copyProperties(userInfo,videoVo);
            list.add(videoVo);
        }
        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);
    }

    @Reference
    private PublishApi publishApi;

    public ResponseEntity queryPublishByUserId(Integer page, Integer pagesize, Long userId, Integer state) {
        PageResult pageResult =  publishApi.queryPublishByUserId(page,pagesize,userId,state);
        List<Publish> publishList = (List<Publish>) pageResult.getItems();

        List<Movements> movementsList = new ArrayList<>();
        for (Publish publish : publishList) {
            UserInfo userInfo = userInfoApi.findById(publish.getUserId());
//            因为测试数据比较乱，所以有可能查不到用户
            if(userInfo==null){
                continue;
            }
            Movements movements = publishAndUserInfoToMovements(publish,userInfo);
            movementsList.add(movements);
        }
        pageResult.setItems(movementsList);
        return ResponseEntity.ok(pageResult);


    }


    //    提取出来的公共的代码：把publish和UserInfo转成movements
    private Movements publishAndUserInfoToMovements(Publish publish, UserInfo userInfo) {
        Movements movements = new Movements();
        BeanUtils.copyProperties(userInfo, movements);
        if (userInfo.getTags() != null) {
            movements.setTags(userInfo.getTags().split(","));
        }
        BeanUtils.copyProperties(publish, movements);
        movements.setId(publish.getId().toString());
        movements.setImageContent(publish.getMedias().toArray(new String[]{}));
        movements.setDistance("500米");
//        这里有个坑  yapi中的API说明中这个值是一个Integer 举例：1598608534811 但是根本不是这样
//        其实要的值是字符串，并且格式是 ：2019-12-01 12:10
        movements.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm"));

        return movements;
    }

    public ResponseEntity queryPublishById(String publishId) {
        Publish publish = publishApi.findById(publishId);
//        publish--->Movements
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        Movements movements = publishAndUserInfoToMovements(publish, userInfo);
        return ResponseEntity.ok(movements);
    }

    @Reference
    private CommentApi commentApi;

    public ResponseEntity queryPublishComments(Integer page, Integer pagesize, String publishId) {
        PageResult pageResult = commentApi.findAll(page, pagesize, publishId,2);
        List<Comment> items = (List<Comment>) pageResult.getItems();

//        Comment--->CommentVo
        List<CommentVo> list = new ArrayList<>();

        CommentVo commentVo = null;
        for (Comment comment : items) {
            commentVo = new CommentVo();
            UserInfo userInfo = userInfoApi.findById(comment.getUserId());
            commentVo.setNickname(userInfo.getNickname());
            commentVo.setAvatar(userInfo.getAvatar());
            commentVo.setId(comment.getId().toString());
            commentVo.setContent(comment.getContent());
            commentVo.setCreateDate(new DateTime(comment.getCreated()).toString("HH:mm") );
            commentVo.setLikeCount(comment.getLikeCount()); //当前评论的点赞数据

            list.add(commentVo);
        }
        pageResult.setItems(list);
        System.out.println(pageResult);
        return ResponseEntity.ok(pageResult);
    }
    //冻结用户
    @Reference
    private    UserFreezeApi userFreezeApi;

    public ResponseEntity freeze(Long userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        UserFreeze userFreeze = new UserFreeze();
        userFreeze.setUserId(userId);
        userFreeze.setFreezingTime(freezingTime);
        userFreeze.setFreezingRange(freezingRange);
        userFreeze.setReasonsForFreezing(reasonsForFreezing);
        userFreeze.setFrozenRemarks(frozenRemarks);
        //保存到表中
        userFreezeApi.save(userFreeze);
        //查询一下freezingRange的值
        userFreeze=  userFreezeApi.findById(userId);


        UserInfo userInfo= userInfoApi.findById(userId);
        userInfo.setUserStatus("2");//1.代表正常2.冻结
        userInfoApi.update(userInfo);

        //冻结完用户开启定时任务
        timerUnFreeze(userId);

        return ResponseEntity.ok(null);
    }
    //用户解冻
    @Reference
    private UserUnfreezeApi userUnfreezeApi;
    public ResponseEntity unfreeze(Long userId, String reasonsForThawing,String frozenRemarks) {
        UserUnfreeze userUnfreeze = new UserUnfreeze();
        userUnfreeze.setUserId(userId);
        userUnfreeze.setReasonsForThawing(reasonsForThawing);
        userUnfreeze.setFrozenRemarks(frozenRemarks);
        //保存到解冻表中
        userUnfreezeApi.save(userUnfreeze);

        //还需要把userInfo中的Userstatus字段设置为1
        UserInfo userInfo= userInfoApi.findById(userId);
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        //需要把tb_user_freeze中的单条数据删除
        userFreezeApi.deleteById(userId);
        return ResponseEntity.ok(null);
    }
    //定时解除冻结
    private void timerUnFreeze(Long userId){
        String reasonsForThawing = "解冻原因";
        String frozenRemarks="冻结时间到，自动解封";
        //创建定时器,冻结时间1位冻结3天，2位冻结7天，3位永久
        UserFreeze userfreeze = userFreezeApi.findById(userId);
        Integer freezingTime = userfreeze.getFreezingTime();

        Timer t = new Timer();

        if (freezingTime==1) {
            t.schedule(new TimerTask() {
                @Override
                public void run() {
                    //先判断该用户是否已经手动解冻
                    UserInfo userInfo = userInfoApi.findById(userId);
                    if(!userInfo.getUserStatus().equals("1")){
                        //执行解冻方法
                        unfreeze(userId,reasonsForThawing,frozenRemarks);
                    }

                }
            },1000*30);
        }
        if (freezingTime==2) {
            t.schedule(new TimerTask() {
                @Override
                public void run() {
                    //先判断该用户是否已经手动解冻
                    UserInfo userInfo = userInfoApi.findById(userId);
                    if(!userInfo.getUserStatus().equals("1")){
                        //执行解冻方法
                        unfreeze(userId,reasonsForThawing,frozenRemarks);
                    }

                }
            },1000*60);
        }
        if(freezingTime==3){
            return;
        }
    }

    /**
     * 动态通过
     * @param publishIds 圈子动态id
     * @return
     */

    public ResponseEntity pass(String[] publishIds) {
        //如果长度不=0，publishIds里有数据
        if(publishIds != null ){
            for (String publishId : publishIds) {
                //根据publishId进行修改state方法
                publishApi.updatePublishState(publishId,1);
            }
        }
        return ResponseEntity.ok("message");
    }
    /**
     * 动态审核拒绝
     * @param publishIds 圈子的动态Id
     * @return
     */
    public ResponseEntity reject(String[] publishIds) {
        if(publishIds != null ){
            for (String publishId : publishIds) {
                publishApi.updatePublishState(publishId,2);
            }
        }
        return ResponseEntity.ok("message");
    }

}